package mips.instructions;

/**
 * <code>SLT</code> instruction<br/>
 * Set On Less Than<br/>
 * @author jnmartin84@gmail.com
 */
public class SLT extends Instruction {

	private static final SLT INSTANCE = new SLT();
	private static final String INSTRUCTION_NAME = "SLT";
	
	private SLT(){}

	public static final SLT getInstance() {
		return INSTANCE;
	}

	/**
	 * <b>Format:</b><br/>
	 * SLT rd, rs, rt<br/><br/>
	 * <b>Description:</b><br/>
	 * The contents of general register rt are subtracted from the contents of<br/>
	 * general register rs. Considering both quantities as signed integers, if the<br/>
	 * contents of general register rs are less than the contents of general register<br/>
	 * rt, the result is set to one; otherwise the result is set to zero.<br/><br/>
	 * The result is placed into general register rd.<br/><br/>
	 * No integer overflow exception occurs under any circumstances. The<br/>
	 * comparison is valid even if the subtraction used during the comparison<br/>
	 * overflows.<br/><br/>
	 * <b>Operation:</b><br/>
	 * T: if GPR[rs] < GPR[rt] then<br/>
	 * GPR[rd] &larr; 0<sup>31</sup> || 1<br/>
	 * else<br/>
	 * GPR[rd] &larr; 0<sup>32</sup><br/>
	 * endif
	 */
	@Override
	public final void execute(final int instruction) {

		final int rs = (instruction >> 21) & 0x0000001F;
		final int rt = (instruction >> 16) & 0x0000001F;
		final int rd = (instruction >> 11) & 0x0000001F;

		mips.R4300i.GPR[rd] = (mips.R4300i.GPR[rs] < mips.R4300i.GPR[rt]) ? 1 : 0;
		
		mips.R4300i.PC = mips.R4300i.nPC;
		mips.R4300i.nPC = mips.R4300i.PC + 4;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String emit(final int instruction) {
		
		final int rs = (instruction >> 21) & 0x0000001F;
		final int rt = (instruction >> 16) & 0x0000001F;
		final int rd = (instruction >> 11) & 0x0000001F;
		
		return 	"		mips.CPU.GPR["+rd+"] = (mips.CPU.GPR["+rs+"] < mips.CPU.GPR["+rt+"]) ? 1 : 0;\n" + 
				"		\n" + 
				"		mips.CPU.PC = mips.CPU.nPC;\n" + 
				"		mips.CPU.nPC = mips.CPU.PC + 4;\n";
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName(final int instruction) {
		return getName();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName() {
		return INSTRUCTION_NAME;
	}
}